import React, { useState, useEffect, useMemo, useRef } from 'react';
import { Select, Spin } from 'antd';
import { debounce } from 'lodash';
import styles from './index.module.less';

function DebounceSelect({ needFetchFirst, fetchOptions, dataContent, debounceTimeout = 400, showPrefix, className, style, onChange, ...props }) {
  const [fetching, setFetching] = useState(false);
  const [options, setOptions] = useState([]);
  const fetchRef = useRef(0);
  const timerId = useRef(undefined);

  useEffect(() => {
    if (needFetchFirst) {
      if (timerId?.current && clearTimeout(timerId.current));
      timerId.current = setTimeout(() => {
        debounceFetcher('');
      }, 500)
    }
    return () => {
      if (timerId?.current && clearTimeout(timerId.current));
    }
  }, [])

  const debounceFetcher = useMemo(() => {
    const loadOptions = (value) => {
      fetchRef.current += 1;
      const fetchId = fetchRef.current;
      setOptions([]);
      setFetching(true);
      fetchOptions(value).then((newOptions) => {
        if (fetchId !== fetchRef.current) {
          // for fetch callback order
          return;
        }

        setOptions(newOptions);
        setFetching(false);
      });
    };

    return debounce(loadOptions, debounceTimeout);
  }, [fetchOptions, debounceTimeout]);

  //选中值得时候增加前缀
  const [prefixConfig, setPreFixConfig] = useState({
    style,
    className
  })

  //点击变更
  const handleChange = (val) => {
    if (showPrefix) {
      if (val || val == 0) {
        const fontSize = 12;
        const textWidth = dataContent.length * fontSize + fontSize;
        const styleSelect = {
          "--prefix-select-padding-left": textWidth + "px",
          "--prefix-select-font-size": fontSize + "px",
        };
        setPreFixConfig({
          style: { ...styleSelect, ...style },
          className: className + ' ' + styles.prefix_select,
        })
      } else {
        setPreFixConfig({
          style,
          className
        })
      }
    }
    onChange(val);
  }

  return (
    <Select
      labelInValue
      filterOption={false}
      onChange={handleChange}
      onSearch={debounceFetcher}
      data-content={dataContent}
      notFoundContent={fetching ? <Spin size="small" /> : '暂无数据'}
      {...prefixConfig}
      {...props}
      options={options}
      defaultValue={props.defaultValue}
    />
  );
}

export default React.memo(DebounceSelect, () => true);